<?php

namespace lc\middleware;

use app\Auth;
use app\models\factory\Admin as factoryAdmin;
use app\models\warehouse\Admin as warehouseAdmin;
use app\models\factory\User as factoryUser;
use lc\cache\redis\Redis;
use lc\helpers\Helper;
use lc\helpers\Response;
use think\facade\Config;
use think\facade\Cookie;

class CheckAuth
{
    public function handle($request, \Closure $next)
    {
        $authConfig = Config::get('lc.auth');
        $routeGroup = $request->rule()->getParent()->getName();

        switch ($routeGroup) {
            case 'api':
                $config = $authConfig['api'];
                if (!Helper::isWeixin() && !empty($config['default'])) {
                    $userId = $config['default'];
                } else {
                    switch ($config['type']) {
                        case 'miniapp':
                            $userId = $request->header($config['key']);
                            break;
                        case 'h5':
                        default:
                            $key    = env('id') . '_user_' . Config::get('lc.auth.api.key');
                            $userId = Helper::decrypt(Cookie::get($key));
                            break;
                    }
                }

                if ($config['is_redis_open']) {
                    $redis = Redis::instance();
                    $redis->select(Config::get('lc.redis.db'));
                    $rdsUser = $redis->hGet(env('id') . '_users', $userId);
                }
                $user = !empty($rdsUser) ? json_decode($rdsUser) : User::where($config['user_key'], $userId)->find();

                if (!in_array($request->rule()->getRule(), $config['ignore_api']) && !$user) {
                    return Response::unLogin();
                }

                if ($user) {
                    if ($config['is_redis_open']) {
                        $redis->hSet(env('id') . '_users', $userId, json_encode($user));
                    }

                    Auth::$userId = $user->{$config['user_id']};
                    Auth::$user   = $user;
                }
                break;
            case 'factory':
                $config = $authConfig['factory'];
                $token  = (!Helper::isWeixin() && !empty($config['default'])) ? $config['default'] : $request->header($config['key']);
                $admin  = factoryAdmin::where($config['user_key'], $token)->find();
                if (!in_array($request->rule()->getRule(), $config['ignore_api']) && (!$admin || $admin->isTokenExpired())) {
                    return Response::unLogin();
                }
                if ($admin) {
                    Auth::$adminId = $admin->{$config['user_id']};
                    Auth::$admin   = $admin;
                }
                break;
            case 'warehouse':
            default:
                $config = $authConfig['warehouse'];
                $token  = (!Helper::isWeixin() && !empty($config['default'])) ? $config['default'] : $request->header($config['key']);
                $admin  = warehouseAdmin::where($config['user_key'], $token)->find();
                if (!in_array($request->rule()->getRule(), $config['ignore_api']) && (!$admin || $admin->isTokenExpired())) {
                    return Response::unLogin();
                }
                if ($admin) {
                    Auth::$adminId = $admin->{$config['user_id']};
                    Auth::$admin   = $admin;
                }
                break;
        }

        return $next($request);
    }
}
